import 'dart:math';

import 'package:flutter/cupertino.dart';

class SizeBuilder extends StatelessWidget {
  final double maxWidth;
  final double maxHeight;
  final double widthPercent;
  final double heightPercent;

  final Widget Function(BuildContext context, BoxConstraints constraints, Widget child) builder;
  final Widget child;

  const SizeBuilder({
    this.maxWidth,
    this.maxHeight,
    this.widthPercent,
    this.heightPercent,
    this.builder,
    this.child,
  });

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        double calcWidth = maxWidth;
        double calcHeight = maxHeight;
        if (widthPercent != null) {
          calcWidth = min(
            maxWidth ?? double.infinity,
            constraints.maxWidth * widthPercent,
          );
        }
        if (heightPercent != null) {
          calcHeight = min(
            maxHeight ?? double.infinity,
            constraints.maxHeight * heightPercent,
          );
        }

        if (builder != null) {
          return builder(context, constraints, child);
        }

        return ConstrainedBox(
          constraints: BoxConstraints(
            minWidth: calcWidth ?? constraints.minWidth,
            maxWidth: calcWidth ?? constraints.maxWidth,
            minHeight: calcHeight ?? constraints.minHeight,
            maxHeight: calcHeight ?? constraints.maxHeight,
          ),
          child: child,
        );
      },
    );
  }
}
